package cn.wolfcode.wolf2w.business.Repository;

import cn.wolfcode.wolf2w.business.domain.Strategy;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class StrategyRepository {
    private static final String INDEX="strategy";
    @Autowired
    private RestHighLevelClient client;
    public List<Strategy> search(String query, int size) throws IOException {
        SearchSourceBuilder ssb = new SearchSourceBuilder()
                .query(QueryBuilders.multiMatchQuery(query, "title", "subtitle", "summary"))
                .size(size);
        SearchRequest request = new SearchRequest(INDEX).source(ssb);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        List<Strategy> strategies = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit);
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String title = sourceAsMap.get("title").toString();

            String subtitle = sourceAsMap.get("subTitle").toString();
            String summary = sourceAsMap.get("summary").toString();
            Strategy strategy = new Strategy();
            strategy.setTitle(title);
            strategy.setSubTitle(subtitle);
            strategy.setSummary(summary);
            strategies.add(strategy);
        }
        return strategies;
    }
}
